package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.ObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.*;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ServletContext ctx;

    public void save(Employee employee, Long[] roleIds) {
        //初始化密码
        employee.setPassword("1");
        //员工的入职时间为录入时间
        employee.setHiredate(new Date());
        //初始化员工状态
        employee.setState(CRMConstant.Employee.STATE_NORMAL);

        employeeMapper.insert(employee);
        List<Role> roles = employee.getRoles();
        if (roles != null) {
            for (Role role : roles) {
                employeeMapper.saveEmployeeRoleRelation(employee.getId(), role.getId());
            }
        }
    }

    public void delete(Long id) {
        if (id != null) {
            employeeMapper.deleteByPrimaryKey(id);
            employeeMapper.deleteEmployeeRoleRelationByEmployee(id);

        }

    }

    public void update(Employee employee, Long[] roleIds) {
        employeeMapper.updateByPrimaryKey(employee);
        List<Role> roles = employee.getRoles();
        employeeMapper.deleteEmployeeRoleRelationByEmployee(employee.getId());
        if (roles != null) {
            for (Role role : roles) {
                employeeMapper.saveEmployeeRoleRelation(employee.getId(), role.getId());
            }
        }
    }

    public Employee get(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    public List<Employee> getAll() {

        return employeeMapper.selectAll();
    }

    public PageResult<Employee> query(ObjectQuery qo) {
        int totalCount = employeeMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult<Employee>(totalCount, Collections.<Employee>emptyList());
        }


        return new PageResult<Employee>(totalCount, employeeMapper.queryForList(qo));
    }

    public void batchDelete(Long[] ids) {
        if (ids != null) {
            employeeMapper.batchDelete(ids);
          /*  for (Long id : ids) {
                employeeMapper.deleteEmployeeRoleRelationByEmployee(id);
            }
*/
        }
    }

    public void selectUsernamePassword(String username, String password) {
        Employee employee = employeeMapper.selectUsernamePassword(username, password);
        if (employee == null) {
            //没此用户
            throw new CheckUsernamePasswordException("账户密码错误");
        }
        //静态方法 RequestContextHolder.getRequestAttributes()
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servicletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        //共享用户信息
        servicletRequestAttributes.getRequest().getSession().setAttribute("EMPLOYEE_IN_SESSION", employee);
        //获取该对象权限表达式
        Set<String> permissions = employeeMapper.selectPermissionsByEmployeeId(employee.getId());
        servicletRequestAttributes.getRequest().getSession().setAttribute("EXPRESSION_IN_SESSION", permissions);
    }

    public Employee selectUsername(String username) {
        return employeeMapper.selectUsername(username);
    }

    public void changState(Long id) {
        employeeMapper.changState(id);
    }

    //修改密码的方法
    public JsonResult changePassword(String oldOne, String newOne) {
        JsonResult json = new JsonResult();
        Employee employee = UserContext.getEmployeeInSession();
        //如果当前登陆的用户的密码与旧的密码对不上就抛出异常
        if (!employee.getPassword().equals(oldOne)) {
            json.markErrorMsg("旧的密码不正确");
        } else {
            //如果对得上就进入持久层修改密码
            employeeMapper.changePassword(employee.getId(), newOne);
        }
        return json;
    }

    //上传图片
    public Map<Object, Object> uploadHeadImg(MultipartFile file) {

        Map<Object, Object> newimgPath = new HashMap<>();
        //先判断这个文件为不为空
        Employee employee = UserContext.getEmployeeInSession();
        if (file != null && file.getSize() != 0) {
            //判断原来有没有图片, 如果有就把它删除
            //发sql根据该用户id查询中间表是否有记录,如果有,就把记录和文件删除
            Map<Object, Object> map = employeeMapper.getImgSrc(employee.getId());
            if (map != null) {
                UploadUtil.deleteFile(ctx, (String) map.get("ImgPath"));
                employeeMapper.deleteImgPath(employee.getId());
            }
            //删除后重新保存图片
            String location = UploadUtil.upload(file, ctx.getRealPath("/static/upload"));
            //保存图片路径到表中
            employeeMapper.uploadHeadImg(location, employee.getId());

        //保存完成后再从数据库中查一次图片的路径
         newimgPath = employeeMapper.getImgSrc(employee.getId());
        }
        //如果该路径是存在的, 那么就把路径返回给前台
        return newimgPath;
    }

    public Map<Object, Object> getHeadImg() {
        Employee employee = UserContext.getEmployeeInSession();
        Map<Object, Object> map = employeeMapper.getImgSrc(employee.getId());
        return map;
    }


}
